Shader "Kun URP/Test/Wireframe"
{
    Properties
    {
        _WireframeColor ("Wireframe Color", Color) = (0, 0, 0, 1)
        _WireframeSmoothing ("Wireframe Smoothing", Range(0, 10)) = 1
		_WireframeThickness ("Wireframe Thickness", Range(0, 10)) = 1
    }
    SubShader
    {
        Tags
        {
            "RenderPipeline"="UniversalRenderPipeline"
        }

        HLSLINCLUDE
        ENDHLSL

        Pass
        {
            HLSLPROGRAM

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            #pragma vertex vert
            #pragma geometry geom
            #pragma fragment frag
            
            float4 _WireframeColor;
            float _WireframeSmoothing;
            float _WireframeThickness;

            struct Attributes
            {
                float4 positionOS   : POSITION;
            };

            struct GeometryPoint
            {
                float4 positionCS   : SV_POSITION;
            };

            struct Varyings
            {
                float4 positionCS               : SV_POSITION;
                float2 barycentricCoordinates   : TEXCOORD0;
            };

            GeometryPoint vert(Attributes input)
            {
                GeometryPoint output;
                output.positionCS = TransformObjectToHClip(input.positionOS.xyz);
                return output;
            }

            [maxvertexcount(3)]
            void geom(triangle GeometryPoint input[3], inout TriangleStream<Varyings> stream)
            {
                Varyings output[3];
                output[0].positionCS = input[0].positionCS;
                output[1].positionCS = input[1].positionCS;
                output[2].positionCS = input[2].positionCS;
                output[0].barycentricCoordinates = float2(1, 0);
                output[1].barycentricCoordinates = float2(0, 1);
                output[2].barycentricCoordinates = float2(0, 0);
                stream.Append(output[0]);
                stream.Append(output[1]);
                stream.Append(output[2]);
            }

            half4 frag(Varyings input) : SV_TARGET
            {
                float3 barys;
                barys.xy = input.barycentricCoordinates;
                barys.z = 1 - barys.x - barys.y;
                float3 deltas = fwidth(barys);
                float3 smoothing = deltas * _WireframeSmoothing;
                float3 thickness = deltas * _WireframeThickness;
                barys = smoothstep(thickness, thickness + smoothing, barys);
                float minBary = min(barys.x, min(barys.y, barys.z));
                return lerp(_WireframeColor, float4(1, 1, 1, 1), minBary);
            }

            ENDHLSL
        }
    }
}